/**
 * 永久层
 */
import dbConfig from '../config/sql-server'
import request from '../controller/request'
import {successStatus,errorStatus} from '../plugins/status'
import {secretKey} from '../plugins/secret'
import jwt from 'jsonwebtoken'
export function findLogin (username,password,req,res) {
  dbConfig(`SELECT * FROM t_user WHERE username='${username}' and password='${password}'`,[],(err,data) => {
    if (data) {
      let resToken = jwt.sign({id: data[0].id},secretKey,{expiresIn: '2h'})
      successStatus.RESULT.data = {
        token: resToken
      }
      req.session.userInfo = 'Bearer ' + successStatus.RESULT.data
      res.status(200).json(successStatus.RESULT)
    } else {
      errorStatus.RESULT.msg = "用户名或密码错误"
      res.send(JSON.stringify(errorStatus.RESULT))
    }
    
  })
}

export async function findRegistern (username,password,res) {
  const result =  await request(`select * from t_user where username='${username}'`)
  if (result.length > 0) {
    errorStatus.RESULT.msg = "用户名已存在，请重新注册"
    res.status(201).json(errorStatus.RESULT)
  } else {
    // 连接数据库
    dbConfig("insert into t_user (id,username,password) values(null,?,?)",[username,password],(err,data) => {
      if (data != undefined) {
        successStatus.RESULT.data = {
          msg: "注册成功!"
        }
        res.status(200).json(successStatus.RESULT)
      } else {
        errorStatus.RESULT.msg = "未知错误，请重新注册"
        res.status(201).json(errorStatus.RESULT)
      }
    })
  }
}

export function findUserList (res){
  request("SELECT id,username,position FROM t_user",[]).then(data => {
      if (data != undefined) {
        successStatus.RESULT.data = data
        res.status(200).json(successStatus.RESULT)
      } else {
        errorStatus.RESULT.msg = "获取列表失败"
        res.send(JSON.stringify(errorStatus.RESULT))
      }
  }).catch(err => {
    errorStatus.RESULT.msg = "获取列表失败"
    res.status(400).json(errorStatus.RESULT.msg)
  })
}